<template>
  <div class="chat-room">
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" 
           :class="['message', message.type === 'user' ? 'user-message' : 'ai-message']">
        <div class="avatar">
          <img v-if="message.type === 'user'" src="../../public/user-icon.svg" alt="'User Avatar'" />
          <img v-else :src="props.aiType ==='manus' ? `../../public/robot-icon.svg` : `../../public/heart-icon.svg`" alt="'AI Avatar'" />
        </div>
        <div class="message-content" v-html="renderMarkdown(message.content)">
        </div>
      </div>
      <div v-if="isThinking" class="message ai-message">
        <div v-if="!isThinking" class="avatar">
          <img :src="props.aiType ==='manus' ? `../../public/robot-icon.svg` : `../../public/heart-icon.svg`" alt="AI Avatar" />
        </div>
        <div class="message-content">
          正在回答...
        </div>
      </div>
    </div>
    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        placeholder="请输入消息..."
        @keyup="handleKeyup"
        size="large"
        type="textarea"
        :autosize="{ minRows: 1, maxRows: 8 }"
      >
      </el-input>
      <el-button @click="sendMessage" type="primary" class="send-button">发送</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import axios from 'axios'
import {useRouter} from "vue-router";
import { marked } from 'marked';

const router = useRouter()

const props = defineProps({
  apiUrl: {
    type: String,
    required: true
  },
  chatId: {
    type: String,
    required: true
  },
  aiType:{
    type: String,
    required: true
  }
})

onMounted(() => {
  console.log('ChatRoom mounted',props.aiType)
  console.log('ChatRoom mounted chatId',props.chatId)
  // messages.value = [
  //   {
  //     type: 'user',
  //     content: '你好'
  //   },
  //   {
  //     type: 'ai',
  //     content: '你好，我是Manus，一个AI助手。'
  //   },
  //   {
  //     type: 'ai',
  //     content: "1. **交个朋友主题撸猫·Tufting打毛线·情侣闺蜜DIY手作**\n" +
  //         "-地址：北京东路与贵州路交叉口东20米\n" +
  //         "-这里提供有趣的活动，比如撸猫和手工制作Tufting打毛线，非常适合情侣互动。\n" +
  //         "\n" +
  //         "2. **和它交个朋友·撸猫·TuftingDIY毛线画·闺蜜情侣下午茶**\n" +
  //         "-地址：北京东路与贵州路交叉口东北20米\n" +
  //         "-另一个撸猫和创意手作的场所，还能享受浪漫的下午茶时光。\n" +
  //         "\n" +
  //         "3. **Perrys(新淮海二店)**\n" +
  //         "-地址：淮海东路45-49号301-307室\n" +
  //         "-这是一家风格独特的餐厅，可以为你们提供美味的食物和舒适的用餐环境。\n" +
  //         "- ![](https://aos-comment.amap.com/B0FFIBT0JA/comment/47D88F8F_C501_4FC1_84C9_C36E0D40576E_L0_001_1500_2000_1727711628053_07466935.jpg)\n" +
  //         "\n" +
  //         "4. **南京路步行街**\n" +
  //         "- 地址：南京东路558号\n" +
  //         "-南京路步行街是逛街购物的好去处，这里有很多店铺可以选择，同时也能感受到上海的繁华。\n" +
  //         "- ![](http://store.is.autonavi.com/showpic/79c863fb97e496744108947dfad8ea10)\n" +
  //         "\n" +
  //         "5. **SFC上影百联影城(大上海店)**\n" +
  //         "- 地址：西藏中路500号8层\n" +
  //         "-您们还可以在这里观看电影，享受轻松愉快的观影体验。\n" +
  //         "- ![](https://aos-comment.amap.com/B00155L1DA/comment/79a23f76b5b87381592c6f50df94c1d0_2048_2048_80.jpg)"
  //   }
  // ]
})

const messages = ref([])
const inputMessage = ref('')
const messagesContainer = ref(null)
const isThinking = ref(false)

const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

watch(messages, () => {
  scrollToBottom()
})

const renderMarkdown = (content) => {
  if (!content) return '';

  // Use the default renderer for now
   return marked(content);
  // 如果不使用库，只处理换行：
//    return content.replace(/\n/g, '<br>');
};

const sendMessage = async () => {
  if (!inputMessage.value.trim()) return

  const userMessage = inputMessage.value
  messages.value.push({
    type: 'user',
    content: userMessage
  })
  inputMessage.value = ''
  isThinking.value = true

  try {
    // SSE 请求
    const eventSource = new EventSource(`${props.apiUrl}?message=${encodeURIComponent(userMessage)}&chatId=${props.chatId}`);

    let aiMessage = '';
     let aiMessageIndex = messages.value.findIndex(msg => msg.type === 'ai' && msg.content === '');
    if(aiMessageIndex === -1) {
      messages.value.push({
        type: 'ai',
        content: ''
      });
      aiMessageIndex = messages.value.length - 1;
    }

    eventSource.onmessage = function(event) {
      // 如果事件数据是 [DONE]，表示流结束
      if (event.data === '[DONE]') {
        isThinking.value = false; // 思考结束
        eventSource.close();
      } else {
        aiMessage += event.data;
        messages.value[aiMessageIndex].content = aiMessage;
         scrollToBottom(); // 实时滚动
      }
    };

    eventSource.onerror = function(error) {
      console.error('EventSource failed:', error);
      isThinking.value = false; // 思考结束
      eventSource.close();
      //  messages.value.push({
      //   type: 'ai',
      //   content: '抱歉，发生了错误，请稍后重试。'
      // })
    };

  } catch (error) {
    console.error('Error sending message:', error)
    isThinking.value = false
    messages.value.push({
      type: 'ai',
      content: '抱歉，发生了错误，请稍后重试。'
    })
  }
}

const handleKeyup = (event) => {
  // 如果按下的是 Enter 键并且没有按下 Shift 键
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault(); // 阻止默认的换行行为
    sendMessage(); // 发送消息
  }
}

</script>

<style scoped>
.chat-room {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0 20px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px 20px 0 10px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
}

.message {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.avatar {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  margin-right: 12px;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-message {
  justify-content: flex-end;
}

.user-message .avatar {
  margin-right: 0;
  margin-left: 12px;
  order: 1;
}

.ai-message {
  justify-content: flex-start;
}

.message-content {
  max-width: 75%;
  padding: 10px 14px;
  border-radius: 18px;
  word-break: break-word;
  overflow-wrap: break-word;
  min-width: 0;
  position: relative;
  line-height: 1.4;
  text-align: left;
}

.message-content img {
  max-width: 100% !important;
  height: auto;
  display: block;
}

.message-content ul,
.message-content ol {
  padding-left: 20px;
}

.message-content li {
  word-break: break-word;
  overflow-wrap: break-word;
}

.user-message .message-content {
  background-color: #409EFF;
  color: white;
}

.ai-message .message-content {
  background-color: #e4e7ed;
  padding: 10px 25px;
  color: #303133;
  border: none;
}

.ai-message .message-content:empty::before {
    content: '...';
    opacity: 0.6;
}

.chat-input {
  padding: 15px 0;
  background-color: #ffffff;
  border-top: 1px solid #ebeef5;
  display: flex;
  align-items: flex-end;
  gap: 15px;
}

.chat-input .el-input {
  flex: 1;
}

.send-button {
  /* 按钮样式可以根据需要调整 */
}

@media (max-width: 768px) {
  .chat-messages {
    padding: 10px 10px 0 10px;
    margin-bottom: 10px;
  }

  .message {
    margin-bottom: 10px;
  }
  
  .message-content {
    max-width: 85%;
    padding: 8px 12px;
    text-align: left;
  }

  .avatar {
    width: 30px;
    height: 30px;
    margin-right: 8px;
  }
  
  .user-message .avatar {
    margin-left: 8px;
  }

  .chat-input {
    padding: 10px 0;
    gap: 10px;
  }
}
</style> 